package com.leapp.sk.ui.fragment

import android.os.Bundle
import cc.vv.lkimcomponent.lkim.bean.LKIMConversation
import com.example.inter.NetWorkInterface
import com.example.mvp.binder.BaseDataBinder
import com.example.mvp.fragment.BaseFragmentMVP
import com.example.mvp.im.observr.NetObsver
import com.leapp.sk.app.SKApplication
import com.leapp.sk.binder.MessageDataBinder
import com.example.util.inter.MsgListUpdateInterface
import com.example.im.server.im.IMChatService
import com.example.util.im.MessageListPresenter
import com.leapp.sk.R
import com.leapp.sk.viewdelegate.MessageDelegate

/**
 * 消息主界面
 * @author  chaohaipeng  on 2018/7/2.
 */
class MessageFragment : BaseFragmentMVP<MessageDelegate>(), MsgListUpdateInterface, NetWorkInterface {
    override fun onConnected(isConnect: Int) {
        if (isConnect==2){
            viewDelegate?.controlNoNetView(true)
        }else{
            viewDelegate?.controlNoNetView(false)
        }
    }


    override fun updateMsg(message: Any) {
        loadConversations()
    }

    /**
     * 消息观察者
     */
    var messagePresenter: MessageListPresenter? = null

    /**
     * 网络观察者
     */
    var netObsver: NetObsver? = null

    /**
     * 数据源
     */
    private val mIMConversation = mutableListOf<LKIMConversation>()

    override fun initView(p0: Bundle?) {
        viewDelegate.initEvent()
        viewDelegate.setTitle(activity.resources.getString(R.string.app_name))
    }
    override fun initData() {
         netObsver = NetObsver()
        netObsver?.start()
        netObsver?.setNetWorkInterfaceListener(this)
        messagePresenter = MessageListPresenter()
        messagePresenter?.setmsgUpdateInterfaceListener(this)
        messagePresenter?.start()
        viewDelegate?.initAdapter(activity, mIMConversation)
        loadConversations()
    }

    override fun onResume() {
        super.onResume()
        loadConversations()
    }

    override fun bindEvenListener() {
    }

    override fun getDelegateClass(): Class<MessageDelegate> {
        return MessageDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return MessageDataBinder()
    }

    override fun onDestroy() {
        super.onDestroy()
        messagePresenter?.stopMessagePresenter()
        netObsver?.stopMessagePresenter()
    }

    /**
     * 加载会话
     */
    private fun loadConversations() {
        IMChatService.getInstance().initConversation(true, object : IMChatService.ConversationInter() {
            override fun success(imConversations: List<LKIMConversation>) {
                SKApplication.getInstance()?.mHandler?.post(object : Runnable {
                    override fun run() {
                        mIMConversation.clear()
                        mIMConversation.addAll(imConversations)
                        viewDelegate?.notifyAdapter()
                    }
                })
            }

            override fun faile() {
            }
        })
    }




}